<template>
  <view class="dashboard-container">
    <!-- 頁面標題 -->
    <view class="page-header">
      <text class="page-title">數據統計</text>
      <text class="page-subtitle">{{ currentDate }}</text>
    </view>

    <!-- 時間維度切換 -->
    <view class="time-tabs">
      <view 
        class="time-tab" 
        :class="{ active: selectedTimeRange === 'total' }" 
        @click="switchTimeRange('total')"
      >
        總計
      </view>
      <view 
        class="time-tab" 
        :class="{ active: selectedTimeRange === 'year' }" 
        @click="switchTimeRange('year')"
      >
        年度
      </view>
      <view 
        class="time-tab" 
        :class="{ active: selectedTimeRange === 'month' }" 
        @click="switchTimeRange('month')"
      >
        月度
      </view>
    </view>

    <!-- 核心數據展示 -->
    <view class="core-stats">
      <!-- 第一行：金額相關 -->
      <view class="stats-row">
        <view class="stat-card primary">
          <view class="stat-icon">💰</view>
          <view class="stat-content">
            <text class="stat-value">{{ formatMoney(valueObj.total_contract_money) }}</text>
            <text class="stat-label">合同金額</text>
          </view>
        </view>
        
        <view class="stat-card success">
          <view class="stat-icon">💵</view>
          <view class="stat-content">
            <text class="stat-value">{{ formatMoney(valueObj.settlement_amount) }}</text>
            <text class="stat-label">結算金額</text>
          </view>
        </view>
      </view>

      <!-- 第二行：收款相關 -->
      <view class="stats-row">
        <view class="stat-card received">
          <view class="stat-icon">✅</view>
          <view class="stat-content">
            <text class="stat-value">{{ formatMoney(valueObj.receivedAmount) }}</text>
            <text class="stat-label">實收金額</text>
          </view>
        </view>
        
        <view class="stat-card warning">
          <view class="stat-icon">⏳</view>
          <view class="stat-content">
            <text class="stat-value">{{ formatMoney(valueObj.ssje) }}</text>
            <text class="stat-label">未收金額</text>
          </view>
        </view>
      </view>

      <!-- 第三行：項目和客戶 -->
      <view class="stats-row">
        <view class="stat-card info">
          <view class="stat-icon">🏗️</view>
          <view class="stat-content">
            <text class="stat-value">{{ valueObj.project_count }}</text>
            <text class="stat-label">項目總數</text>
          </view>
        </view>
        
        <view class="stat-card customers">
          <view class="stat-icon">👥</view>
          <view class="stat-content">
            <text class="stat-value">{{ valueObj.nameList }}</text>
            <text class="stat-label">客戶數量</text>
          </view>
        </view>
      </view>

      <!-- 第四行：狀態統計 -->
      <view class="stats-row">
        <view class="stat-card completed">
          <view class="stat-icon">🎯</view>
          <view class="stat-content">
            <text class="stat-value">{{ valueObj.ywjNum }}</text>
            <text class="stat-label">已完結</text>
          </view>
        </view>
        
        <view class="stat-card processing">
          <view class="stat-icon">🔄</view>
          <view class="stat-content">
            <text class="stat-value">{{ valueObj.skzNum }}</text>
            <text class="stat-label">收款中</text>
          </view>
        </view>
      </view>

      <!-- 第五行：異常統計 -->
      <view class="stats-row">
        <view class="stat-card danger">
          <view class="stat-icon">⚠️</view>
          <view class="stat-content">
            <text class="stat-value">{{ valueObj.ycNum }}</text>
            <text class="stat-label">異常</text>
          </view>
        </view>
        
        <view class="stat-card completed">
          <view class="stat-icon">🎯</view>
          <view class="stat-content">
            <text class="stat-value">{{ valueObj.settled_production_quantityNum }}</text>
            <text class="stat-label">结算生产量</text>
          </view>
        </view>
	</view>
	<view class="stats-row">
		
		<view class="stat-card customers">
		  <view class="stat-icon">🎯</view>
		  <view class="stat-content">
		    <text class="stat-value">{{ valueObj.unsettled_production_quantityNum }}</text>
		    <text class="stat-label">未结算生产量</text>
		  </view>
		</view>
		<view class="stat-card primary">
		  <view class="stat-icon">🎯</view>
		  <view class="stat-content">
		    <text class="stat-value">{{ valueObj.uninvoiced_amountNum }}</text>
		    <text class="stat-label">未开票金额</text>
		  </view>
		</view>
      </view>
    </view>

    <!-- 底部導航 -->
    <custom-tabbar :current="tabIndex" :tabList="tabList" />
  </view>
</template>

<script>
import CustomTabbar from '@/components/custom-tabbar/CustomTabbar.vue'
import { getTabListByRole } from '@/utils/tabberList.js'

export default {
  components: { CustomTabbar },
  data() {
    return {
      tabList: [],
      tabIndex: 0,
      currentDate: '',
      selectedTimeRange: 'total', // total, year, month
      loading: false,
      // 總計數據
      totalData: {
        contractAmount: 0,
        settlementAmount: 0,
        receivedAmount: 0,
        unreceivedAmount: 0,
        totalProjects: 0,
        customerCount: 0,
        completedProjects: 0,
        paymentInProgress: 0,
        abnormalCount: 0,
        paymentCompletionRate: 0
      },
      // 年度數據
      yearData: {
        contractAmount: 0,
        settlementAmount: 0,
        receivedAmount: 0,
        unreceivedAmount: 0,
        totalProjects: 0,
        customerCount: 0,
        completedProjects: 0,
        paymentInProgress: 0,
        abnormalCount: 0,
        paymentCompletionRate: 0
      },
      // 月度數據
      monthData: {
        contractAmount: 0,
        settlementAmount: 0,
        receivedAmount: 0,
        unreceivedAmount: 0,
        totalProjects: 0,
        customerCount: 0,
        completedProjects: 0,
        paymentInProgress: 0,
        abnormalCount: 0,
        paymentCompletionRate: 0
      },
	  valueObj: {
		  
	  }
    }
  },
  computed: {
    currentData() {
      switch (this.selectedTimeRange) {
        case 'year':
          return this.yearData;
        case 'month':
          return this.monthData;
        default:
          return this.totalData;
      }
    }
  },
  onShow() {
    this.initPage();
    this.loadStats();
  },
  onLoad () {
	  this.getProjecStatus()
  },
  methods: {
	  getProjecStatus(){
		  const that = this;
		  uni.request({
		    url: 'https://data.web1995.top/api/project/projectStatistics',
		    method: 'POST',
		    data: {
				time_type: this.selectedTimeRange
			},
		    header: {
		      'token': uni.getStorageSync('sc-token') || ''
		    },
		    success: (res) => {
					console.log(res)
					that.valueObj = res.data.data;
		    }
		  });
	  },
    // 初始化頁面
    initPage() {
      const role = uni.getStorageSync('user-role');
      this.tabList = getTabListByRole(role);
      
      // 獲取當前頁面路徑
      let currentPath = '';
      const pages = getCurrentPages();
      if (pages.length) {
        currentPath = pages[pages.length - 1].route || pages[pages.length - 1].__route__ || '';
      }
      this.tabIndex = this.tabList.findIndex(item => item.pagePath === currentPath);
      
      // 設置當前日期
      this.currentDate = this.formatDate(new Date());
    },

    // 切換時間維度
    switchTimeRange(range) {
      this.selectedTimeRange = range;
	  this.getProjecStatus()
    },

    // 加載統計數據
    async loadStats() {
      this.loading = true;
      try {
        // 先使用假數據展示效果
        this.loadMockData();
        
        // 真實數據加載（暫時註釋）
        // const res = await this.getProjectList();
        // if (res && res.data && res.data.code === 1) {
        //   const projects = res.data.data || [];
        //   this.calculateStats(projects);
        // }
      } catch (error) {
        console.error('加載統計數據失敗:', error);
        uni.showToast({
          title: '數據加載失敗',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 加載假數據
    loadMockData() {
      // 總計數據
      this.totalData = {
        contractAmount: 25800000,
        settlementAmount: 23500000,
        receivedAmount: 18900000,
        unreceivedAmount: 4600000,
        totalProjects: 156,
        customerCount: 89,
        completedProjects: 45,
        paymentInProgress: 18,
        abnormalCount: 12,
        paymentCompletionRate: 73
      };

      // 年度數據（2024年）
      this.yearData = {
        contractAmount: 15800000,
        settlementAmount: 14500000,
        receivedAmount: 11200000,
        unreceivedAmount: 3300000,
        totalProjects: 98,
        customerCount: 56,
        completedProjects: 28,
        paymentInProgress: 12,
        abnormalCount: 8,
        paymentCompletionRate: 71
      };

      // 月度數據（當前月）
      this.monthData = {
        contractAmount: 2800000,
        settlementAmount: 2600000,
        receivedAmount: 2100000,
        unreceivedAmount: 500000,
        totalProjects: 18,
        customerCount: 12,
        completedProjects: 6,
        paymentInProgress: 3,
        abnormalCount: 2,
        paymentCompletionRate: 75
      };
    },

    // 獲取項目列表
    getProjectList() {
      return new Promise((resolve, reject) => {
        uni.request({
          url: 'https://data.web1995.top/api/project/getProjectList',
          method: 'POST',
          data: {},
          header: {
            'token': uni.getStorageSync('sc-token') || ''
          },
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },

    // 計算統計數據
    calculateStats(projects) {
      console.log('計算統計數據:', projects);
      
      // 計算總計數據
      this.calculateTotalData(projects);
      
      // 計算年度數據
      this.calculateYearData(projects);
      
      // 計算月度數據
      this.calculateMonthData(projects);
    },

    // 計算總計數據
    calculateTotalData(projects) {
      this.totalData = {
        contractAmount: projects.reduce((sum, p) => sum + (parseFloat(p.contract_money) || 0), 0),
        settlementAmount: projects.reduce((sum, p) => sum + (parseFloat(p.settlement_amount) || 0), 0),
        receivedAmount: projects.reduce((sum, p) => sum + (parseFloat(p.actual_received_total_amount) || 0), 0),
        unreceivedAmount: 0,
        totalProjects: projects.length,
        customerCount: new Set(projects.map(p => p.customer_name).filter(Boolean)).size,
        completedProjects: projects.filter(p => p.status === '已完結').length,
        paymentInProgress: projects.filter(p => p.status === '收款中').length,
        abnormalCount: projects.filter(p => p.status === '異常').length,
        paymentCompletionRate: 0
      };

      // 計算未收金額
      this.totalData.unreceivedAmount = this.totalData.settlementAmount - this.totalData.receivedAmount;
      
      // 計算收款完成率
      if (this.totalData.settlementAmount > 0) {
        this.totalData.paymentCompletionRate = Math.round(
          (this.totalData.receivedAmount / this.totalData.settlementAmount) * 100
        );
      }
    },

    // 計算年度數據
    calculateYearData(projects) {
      const currentYear = new Date().getFullYear();
      const yearProjects = projects.filter(p => {
        if (!p.createtime) return false;
        const createDate = new Date(p.createtime);
        return createDate.getFullYear() === currentYear;
      });

      this.yearData = {
        contractAmount: yearProjects.reduce((sum, p) => sum + (parseFloat(p.contract_money) || 0), 0),
        settlementAmount: yearProjects.reduce((sum, p) => sum + (parseFloat(p.settlement_amount) || 0), 0),
        receivedAmount: yearProjects.reduce((sum, p) => sum + (parseFloat(p.actual_received_total_amount) || 0), 0),
        unreceivedAmount: 0,
        totalProjects: yearProjects.length,
        customerCount: new Set(yearProjects.map(p => p.customer_name).filter(Boolean)).size,
        completedProjects: yearProjects.filter(p => p.status === '已完結').length,
        paymentInProgress: yearProjects.filter(p => p.status === '收款中').length,
        abnormalCount: yearProjects.filter(p => p.status === '異常').length,
        paymentCompletionRate: 0
      };

      this.yearData.unreceivedAmount = this.yearData.settlementAmount - this.yearData.receivedAmount;
      
      if (this.yearData.settlementAmount > 0) {
        this.yearData.paymentCompletionRate = Math.round(
          (this.yearData.receivedAmount / this.yearData.settlementAmount) * 100
        );
      }
    },

    // 計算月度數據
    calculateMonthData(projects) {
      const currentDate = new Date();
      const currentYear = currentDate.getFullYear();
      const currentMonth = currentDate.getMonth();
      
      const monthProjects = projects.filter(p => {
        if (!p.createtime) return false;
        const createDate = new Date(p.createtime);
        return createDate.getFullYear() === currentYear && createDate.getMonth() === currentMonth;
      });

      this.monthData = {
        contractAmount: monthProjects.reduce((sum, p) => sum + (parseFloat(p.contract_money) || 0), 0),
        settlementAmount: monthProjects.reduce((sum, p) => sum + (parseFloat(p.settlement_amount) || 0), 0),
        receivedAmount: monthProjects.reduce((sum, p) => sum + (parseFloat(p.actual_received_total_amount) || 0), 0),
        unreceivedAmount: 0,
        totalProjects: monthProjects.length,
        customerCount: new Set(monthProjects.map(p => p.customer_name).filter(Boolean)).size,
        completedProjects: monthProjects.filter(p => p.status === '已完結').length,
        paymentInProgress: monthProjects.filter(p => p.status === '收款中').length,
        abnormalCount: monthProjects.filter(p => p.status === '異常').length,
        paymentCompletionRate: 0
      };

      this.monthData.unreceivedAmount = this.monthData.settlementAmount - this.monthData.receivedAmount;
      
      if (this.monthData.settlementAmount > 0) {
        this.monthData.paymentCompletionRate = Math.round(
          (this.monthData.receivedAmount / this.monthData.settlementAmount) * 100
        );
      }
    },

    // 格式化金額
    formatMoney(amount) {
      if (!amount && amount !== 0) return '0';
      const num = parseFloat(amount);
      if (isNaN(num)) return '0';
      return num.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    },

    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}年${month}月${day}日`;
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  min-height: 100vh;
  background: #f5f6fa;
  padding: 30rpx 30rpx 120rpx 30rpx;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 30rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.page-subtitle {
  font-size: 24rpx;
  color: #999;
}

/* 時間維度切換 */
.time-tabs {
  display: flex;
  background: #fff;
  border-radius: 12rpx;
  padding: 8rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.time-tab {
  flex: 1;
  text-align: center;
  padding: 16rpx 0;
  font-size: 28rpx;
  color: #666;
  border-radius: 8rpx;
  transition: all 0.3s ease;
}

.time-tab.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  font-weight: bold;
}

/* 核心數據展示 */
.core-stats {
  margin-bottom: 30rpx;
}

.stats-row {
  display: flex;
  gap: 24rpx;
  margin-bottom: 24rpx;
}

/* 空卡片樣式 */
.stat-card.empty {
  background: transparent;
  box-shadow: none;
  border: 2rpx dashed #e0e0e0;
}

.stat-card.empty .stat-content {
  text-align: center;
}

.stat-card.empty .stat-value,
.stat-card.empty .stat-label {
  color: #ccc;
}

.stat-card {
  flex: 1;
  background: #fff;
  border-radius: 20rpx;
  padding: 32rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
  min-height: 120rpx;
}

.stat-card:active {
  transform: scale(0.98);
}

.stat-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  flex-shrink: 0;
  font-size: 36rpx;
}

.stat-content {
  flex: 1;
  min-width: 0;
}

.stat-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 卡片顏色主題 */
.stat-card.primary {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border-left: 6rpx solid #2196f3;
}

.stat-card.primary .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-card.success {
  background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%);
  border-left: 6rpx solid #4caf50;
}

.stat-card.success .stat-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-card.received {
  background: linear-gradient(135deg, #e1f5fe 0%, #b3e5fc 100%);
  border-left: 6rpx solid #03a9f4;
}

.stat-card.received .stat-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-card.warning {
  background: linear-gradient(135deg, #fff3e0 0%, #ffcc80 100%);
  border-left: 6rpx solid #ff9800;
}

.stat-card.warning .stat-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-card.info {
  background: linear-gradient(135deg, #f3e5f5 0%, #e1bee7 100%);
  border-left: 6rpx solid #9c27b0;
}

.stat-card.info .stat-icon {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.stat-card.customers {
  background: linear-gradient(135deg, #fce4ec 0%, #f8bbd9 100%);
  border-left: 6rpx solid #e91e63;
}

.stat-card.customers .stat-icon {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
}

.stat-card.completed {
  background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%);
  border-left: 6rpx solid #4caf50;
}

.stat-card.completed .stat-icon {
  background: linear-gradient(135deg, #a8c0ff 0%, #3f2b96 100%);
}

.stat-card.processing {
  background: linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%);
  border-left: 6rpx solid #ffc107;
}

.stat-card.processing .stat-icon {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
}

.stat-card.danger {
  background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
  border-left: 6rpx solid #f44336;
}

.stat-card.danger .stat-icon {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
}


/* 響應式設計 */
@media (max-width: 750rpx) {
  .stats-row {
    flex-direction: column;
  }
  
  .stats-row.single {
    align-items: center;
  }
}
</style>